package com.yiding.sys.config;

import com.yiding.sys.common.auth.AuthRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author War horse imwarhorse@aliyun.com
 * Date: 2020/8/7
 * Description: No Description
 */

@Configuration
public class ShiroConfig {

	@Bean("credentialsMatcher")
	public CredentialsMatcher credentialsMatcher() {
		HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
		credentialsMatcher.setHashAlgorithmName("MD5");
		credentialsMatcher.setHashIterations(128);
		return credentialsMatcher;
	}

	@Bean("realm")
	public Realm realm(@Qualifier("credentialsMatcher") CredentialsMatcher credentialsMatcher) {
		AuthRealm authRealm = new AuthRealm();

		authRealm.setCredentialsMatcher(credentialsMatcher);

		return authRealm;
	}

	@Bean("securityManager")
	public SecurityManager securityManager(@Qualifier("realm") Realm realm) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(realm);
		return securityManager;
	}

	@Bean("shiroFilter")
	public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager securityManager) {
		ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
		shiroFilter.setSecurityManager(securityManager);

		// 无权限页面
		// 会到request handler中查找mapping了该url的handler进行处理
		shiroFilter.setUnauthorizedUrl("/unauthorized");
		// 登录页
		shiroFilter.setLoginUrl("/signin");

		Map<String, String> filterChain = new LinkedHashMap<>();
		filterChain.put("/sys/login", "anon");
		filterChain.put("/signin", "anon");

		// 静态资源文件拦截路径
		filterChain.put("/dist/**", "anon");
		filterChain.put("/css/**", "anon");
		filterChain.put("/js/**", "anon");
		filterChain.put("/image/**", "anon");

		// 其他路径
		filterChain.put("/**", "authc");

		shiroFilter.setFilterChainDefinitionMap(filterChain);
		return shiroFilter;
	}

}
